package com.wally.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * 客户端
 * 
 * @author LaiGuiLiang 2018/01/23
 *
 */
@Slf4j
public class TimeClient {
	
	public void connect(int port ,String host) throws Exception{
		//配置客户端NIO线程组
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();// 客户端辅助启动类Bootstrap
			b.group(group).channel(NioSocketChannel.class)// 与服务端(NioServerSocketChannel)不同的是它的Channel设置为NioSocketChannel
				.option(ChannelOption.TCP_NODELAY, true)
				.handler(new ChannelInitializer<SocketChannel>() {//添加Handler,其作用是当创建NioSocketChannel成功之后，在进行初始化时，将它的ChannelHandler设置到ChannelPipeline中，用于处理I/O事件

					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new TimeClientHandler());
					}
				});
			
			// 发起异步连接操作
			ChannelFuture f = b.connect(host, port).sync();// 客户端辅助类设置完成之后，调用connect方法发起异步连接，然后调用同步方法等待连接成功

			// 等待客户端链路关闭
			f.channel().closeFuture().sync();
		} finally {
			//优雅退出，释放NIO线程组
			group.shutdownGracefully();// 最后，当客户端连接关闭之后，客户端主函数退出，退出之前释放NIO线程组的资源
		}
	}
	
	public static void main(String[] args) throws Exception {
		int port = 8080;
		if(args != null && args.length > 0) {
			try {
				port = Integer.valueOf(port);
			} catch (NumberFormatException e) {
				log.error("异常：{}", e);
			}
		}
		
		new TimeClient().connect(port, "127.0.0.1");
	}

}



































